import Vue from 'vue';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';

Vue.use(VueRouter);

const routes = [
    {
        path: '/emp',
        name: 'emp',
        component: () => import('../views/tea/EmpView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/dept',
        name: 'dept',
        component: () => import('../views/tea/DeptView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/tea/LoginView.vue'),
        meta: { public: true }, // 标记需要认证的页面
    },
    {
        path: '/admin/teas',
        name: 'teas',
        component: () => import('../views/tea/TeaView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/admin/orders',
        name: 'orders',
        component: () => import('../views/tea/OrdersView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/admin/inventorys',
        name: 'inventorys',
        component: () => import('../views/tea/InventorysView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/admin/sales',
        name: 'sales',
        component: () => import('../views/tea/SalesView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/',
        redirect: '/index', // 默认跳转到登录页面
        meta: { public: true }, // 标记为公开页面
    },
    {
        path: '/admin/user',
        name: 'userInfo',
        component: () => import('../views/tea/UserView.vue'),
        meta: {requiresAuth: true}, // 标记需要认证的页面
    },
    {
        path: '/index',
        name: 'indexView',
        component: () => import('../views/tea/IndexView.vue'),
        meta: { public: true }, // 标记为公开页面
    },
    {
        path: '/user/buy',
        name: 'userBuyView',
        component: () => import('../views/tea/UserBuyView.vue'),
        meta: { public: true }, // 标记为公开页面
    },
    {
        path: '/register',
        name: 'registerView',
        component: () => import('../views/tea/RegisterView.vue'),
        meta: { public: true }, // 标记为公开页面
    }
];

const router = new VueRouter({
    mode: 'history', // 使用 history 模式，确保后端支持
    base: process.env.BASE_URL,
    routes,
});

// 路由守卫：认证拦截
router.beforeEach((to, from, next) => {
    const token = Cookies.get('token'); // 从 Cookie 中获取 token

    // 如果目标路由需要认证
    if (to.meta.requiresAuth && !token) {
        if (to.name === 'login') {
            // 如果已经在 login 页面，避免重复跳转
            next();
        } else {
            next({ name: 'login' }); // 跳转到登录页面
        }
    } else {
        next(); // 否则放行
    }
});

export default router;
